package dao

import (
	"bms/db"
	"bms/model"
	"log"
)

func GetBorrowItem(bookId int64, borrowId string) (*model.BorrowItem, error) {
	sql := "select id,borrow_nums,book_id,borrow_id from borrow_items where book_id=? and borrow_id=?"
	row := db.Db.QueryRow(sql, bookId, borrowId)
	borrowItem := &model.BorrowItem{}
	err := row.Scan(&borrowItem.BorrowItemId, &borrowItem.BorrowNums, &borrowItem.BookId, &borrowItem.BorrowId)
	if err != nil {
		return nil, err
	}
	//根据bookId找到book
	book, err := BorrowBook(bookId)
	if err != nil {
		return nil, err
	}
	borrowItem.Book = book
	return borrowItem, nil
}

func GetBorrowItemByBorrowId(borrowId string) []*model.BorrowItem {
	var borrowItems []*model.BorrowItem
	sql := "select id,borrow_nums,book_id,borrow_id,borrow_time from borrow_items where borrow_id=?"
	rows, err := db.Db.Query(sql, borrowId)
	if err != nil {
		return nil
	}
	for rows.Next() {
		borrowItem := &model.BorrowItem{}
		rows.Scan(&borrowItem.BorrowItemId, &borrowItem.BorrowNums, &borrowItem.BookId, &borrowItem.BorrowId, &borrowItem.BorrowTime)
		//根据bookId找到book
		book, _ := BorrowBook(borrowItem.BookId)
		borrowItem.Book = book
		borrowItems = append(borrowItems, borrowItem)
	}

	return borrowItems
}

func UpdateBorrowItemNums(borrowItem *model.BorrowItem) error {
	sql := "update borrow_items set borrow_nums=? where book_id=? and borrow_id=?"
	_, err := db.Db.Exec(sql, borrowItem.BorrowNums, borrowItem.Book.Id, borrowItem.BorrowId)
	if err != nil {
		return err
	}
	return nil
}

func SaveBorrowItem(borrowItem *model.BorrowItem) error {
	sql := "insert into borrow_items(borrow_nums,book_id,borrow_id,borrow_time) values (?,?,?,?)"
	_, err := db.Db.Exec(sql, borrowItem.BorrowNums, borrowItem.Book.Id, borrowItem.BorrowId, borrowItem.BorrowTime)
	log.Println("-------borrowItem.BorrowNums--------", borrowItem.BorrowNums)
	log.Println("----------borrowItem.BookId-------", borrowItem.BookId)
	log.Println("-------borrowItem.BorrowId------", borrowItem.BorrowId)
	if err != nil {
		return err
	}
	return nil
}

func ReturnBookByBorrowItemId(borrowItemId int64) error {
	sql := "delete from borrow_items where id=?"
	_, err := db.Db.Exec(sql, borrowItemId)
	if err != nil {
		return err
	}
	return nil
}

func QueryBorrowItem(borrowItemId int64) bool {
	sql := "select id,borrow_nums,book_id,borrow_id,borrow_time from borrow_items where id=?"
	row := db.Db.QueryRow(sql, borrowItemId)
	borrowItem := &model.BorrowItem{}
	row.Scan(&borrowItem.BorrowItemId, &borrowItem.BorrowNums, &borrowItem.BookId, &borrowItem.BorrowId, &borrowItem.BorrowTime)
	if borrowItem != nil {
		return true
	}
	return false
}
